<template>
  <!-- 卡片头部 -->
  <div class="card-header">
    <!-- 卡片容器 -->
    <el-card class="max-width: 100%">
      <!-- 标题 -->
      <h2>管理员信息</h2>
      <!-- 搜索和添加按钮区域 -->
      <div class="search-add-container" style="display: flex; align-items: center; margin-bottom: 20px;">
        <!-- 搜索输入框 -->
              <el-input
        placeholder="输入管理员姓名查询"
        v-model="searchname"
        @keyup.enter="searchAdmin"
        style="width: 200px; margin-right: 10px;" 
      ></el-input>
        <!-- 查询按钮 -->
        <el-button type="primary" @click="searchAdmin" style="margin-right: 10px;">查询</el-button>
        <!-- 添加按钮 -->
        <el-button type="success" @click="openAdminDialog(true)">添加</el-button>
        <!-- 多选删除按钮 -->
        <el-button type="danger" @click="multiDelete">多选删除</el-button>
      </div>
      <!-- 管理员信息表格 -->
      <el-table
        :data="tableData"
        style="width: 160%"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
        stripe highlight-current-row border
      >
        <!-- 选择列 -->
        <el-table-column type="selection" width="100"></el-table-column>
        <!-- 编号列 -->
        <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
        <!-- 昵称列 -->
        <el-table-column prop="name" label="昵称" width="200"></el-table-column>
        <!-- 生日列 -->
        <el-table-column prop="birthday" label="生日" width="200" :formatter="formatDate"></el-table-column>
        <!-- 性别列 -->
        <el-table-column prop="sex" label="性别" width="250" :formatter="formatSex"></el-table-column>
        <!-- 管理员密码列 -->
        <el-table-column prop="password" label="管理员密码" width="250"></el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="300">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button type="warning" @click="openAdminDialog(false, scope.row)">修改</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" @click="confirmDeleteAdmin(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页显示 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 4, 5, 10]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchedAdmins.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
  <!-- 添加和修改管理员的对话框 -->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="30%"
    @close="resetAdminForm"
  >
    <el-form :model="currentAdminForm">
      <!-- 昵称输入框 -->
      <el-form-item label="昵称" required>
        <el-input v-model="currentAdminForm.name"></el-input>
      </el-form-item>
      <!-- 编号输入框 -->
      <el-form-item label="编号" required>
        <el-input v-model="currentAdminForm.admin_id" disabled></el-input>
      </el-form-item>
      <!-- 生日选择器 -->
      <el-form-item label="生日">
        <el-date-picker v-model="currentAdminForm.birthday" type="date" placeholder="选择生日"></el-date-picker>
      </el-form-item>
      <!-- 性别选择器 -->
      <el-form-item label="性别">
        <el-select v-model="currentAdminForm.sex" placeholder="选择性别">
          <el-option label="男" value="male"></el-option>
          <el-option label="女" value="female"></el-option>
        </el-select>
      </el-form-item>
      <!-- 管理员密码输入框 -->
      <el-form-item label="管理员密码" required>
        <el-input type="password" v-model="currentAdminForm.password"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <!-- 取消按钮 -->
      <el-button @click="dialogVisible = false">取 消</el-button>
      <!-- 确定按钮 -->
      <el-button type="primary" @click="submitAdminForm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  data() {
    return {
      searchname: '', // 搜索框绑定的值
      isAdding: false, // 是否处于添加状态
      dialogVisible: false, // 是否显示对话框
      dialogTitle: '添加管理员', // 对话框标题
      multipleSelection: [], // 多选删除
      pageSize: 3, // 当前页条数
      currentPage: 1, // 当前记录条数
      
      currentAdminForm: {
        name: '',
        admin_id: '',
        birthday: '',
        sex: 'male', // 默认性别为男
        password: '',
      },
      tableData: [], // 表格显示的数据
      admins: [], // 所有管理员数据，用于过滤和删除
      searchedAdmins: [], // 搜索后的结果数组，用于分页
    };
  },
  computed: {
    filteredAdmins() {
      if (!this.searchname) return this.admins;
      return this.searchedAdmins.filter(admin => admin.name.includes(this.searchname));
    },
  },
  methods: {
    // 分页大小改变时的处理函数
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.updateTableData();
    },
    // 当前页码改变时的处理函数
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum;
      this.updateTableData();
    },
    // 更新表格数据
    updateTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      this.tableData = this.filteredAdmins.slice(start, end);
    },
    // 日期格式化函数
    formatDate(row, column, cellValue) {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 性别格式化函数
    formatSex(row, column, cellValue) {
      return cellValue === 'male' ? '男' : '女';
    },
    // 打开管理员对话框
    openAdminDialog(isAdd, admin = null) {
      this.isAdding = isAdd;
      if (isAdd) {
        this.dialogTitle = '添加管理员';
        this.currentAdminForm = {
          name: '',
          admin_id: '',
          birthday: '',
          sex: 'male', // 默认性别为男
          password: '',
        };
      } else {
        this.dialogTitle = '修改管理员';
        this.currentAdminForm = { ...admin };
      }
      this.dialogVisible = true;
    },
    // 重置管理员表单
    resetAdminForm() {
      this.currentAdminForm = {
        name: '',
        admin_id: '',
        birthday: '',
        sex: 'male', // 默认性别为男
        password: '',
      };
      this.isAdding = false;
    },
    // 提交管理员表单
    submitAdminForm() {
      if (this.isAdding) {
        this.saveAdmin();
      } else {
        this.updateAdmin();
      }
    },
    // 保存管理员
    saveAdmin() {
      this.$http.post("/admin/hhl", {
        name: this.currentAdminForm.name,
        birthday: this.currentAdminForm.birthday,
        sex: this.currentAdminForm.sex,
        password: this.currentAdminForm.password
      }).then(response => {
        if (response.data) {
          this.admins.push({
            admin_id: response.data, // 假设后端返回生成的admin_id
            ...this.currentAdminForm,
          });
          this.searchedAdmins.push({ // 添加到搜索结果中
            admin_id: response.data,
            ...this.currentAdminForm,
          });
          this.tableData = [...this.searchedAdmins]; // 更新表格数据
          this.$message.success('新增管理员成功');
          this.dialogVisible = false;
          this.resetAdminForm();
        } else {
          this.$message.error('新增管理员失败');
        }
      }).catch(error => {
        console.error('新增管理员失败', error);
        this.$message.error('新增管理员失败，请稍后再试');
      });
    },
    // 更新管理员信息
    updateAdmin() {
      this.$http.put("/admin/u1", {
        admin_id: this.currentAdminForm.admin_id,
        name: this.currentAdminForm.name,
        birthday: this.currentAdminForm.birthday,
        sex: this.currentAdminForm.sex,
        password: this.currentAdminForm.password
      }).then(response => {
        if (response.data) {
          const index = this.admins.findIndex(admin => admin.admin_id === this.currentAdminForm.admin_id);
          if (index !== -1) {
            this.admins.splice(index, 1, { ...this.currentAdminForm });
            this.searchedAdmins.splice(index, 1, { ...this.currentAdminForm });
            this.tableData = this.searchedAdmins.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
            this.$message.success('管理员信息已更新');
          }
          this.dialogVisible = false;
          this.resetAdminForm();
        } else {
          this.$message.error('更新管理员信息失败');
        }
      }).catch(error => {
        console.error('更新管理员信息失败', error);
        this.$message.error('更新管理员信息失败，请稍后再试');
      });
    },
    // 确认删除管理员
    confirmDeleteAdmin(admin) {
      this.$confirm(`确定要删除管理员 ${admin.name} 吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.deleteAdmin(admin.admin_id);
      }).catch(() => {
        this.$message.info('删除已取消');
      });
    },
    // 删除管理员
    deleteAdmin(admin_id) {
      this.$http.delete(`/admin/d1/${admin_id}`).then(response => {
        if (response.data) {
          this.admins = this.admins.filter(item => item.admin_id !== admin_id);
          this.searchedAdmins = this.searchedAdmins.filter(item => item.admin_id !== admin_id);
          this.tableData = this.searchedAdmins.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
          this.$message.success('删除成功');
        } else {
          this.$message.error('删除失败');
        }
      }).catch(error => {
        console.error('删除管理员失败', error);
        this.$message.error('删除失败，请稍后再试');
      });
    },
    // 多选删除
    multiDelete() {
      this.$confirm('您确定要删除选中的管理员吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const adminIds = this.multipleSelection.map(item => item.admin_id);
        adminIds.forEach(admin_id => {
          this.deleteAdmin(admin_id);
        });
      }).catch(() => {
        this.$message.info('删除已取消');
      });
    },
    // 处理选择变化
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 搜索管理员
    searchAdmin() {
      this.searchname.trim() ? this.searchedAdmins = this.filteredAdmins : this.searchedAdmins = this.admins;
      this.currentPage = 1; // 重置为第一页
      this.updateTableData();
    },
  },
  // 组件挂载后执行
  mounted() {
    this.$http.get("/admin/g1").then(response => {
      this.admins = response.data;
      this.searchedAdmins = response.data;
      this.tableData = this.searchedAdmins.slice(0, this.pageSize);
    }).catch(error => {
      console.error('获取管理员信息失败', error);
      this.$message.error('获取管理员信息失败，请稍后再试');
    });
  }
}
</script>
<style>
</style>
     